<template>
  <view class="audit-page">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="title">审核管理</text>
      <text class="subtitle">当前角色: {{ roleText }}</text>
    </view>

    <!-- 状态筛选 -->
    <view class="status-filter">
      <view class="filter-row">
        <view 
          class="filter-tab" 
          :class="{ active: selectedStatus === 'all' }"
          @click="filterByStatus('all')"
        >
          全部
        </view>
        <view 
          class="filter-tab" 
          :class="{ active: selectedStatus === 'pending' }"
          @click="filterByStatus('pending')"
        >
          待审批
        </view>
        <view 
          class="filter-tab" 
          :class="{ active: selectedStatus === '已签约' }"
          @click="filterByStatus('已签约')"
        >
          已签约
        </view>
        <view 
          class="filter-tab" 
          :class="{ active: selectedStatus === '已完结' }"
          @click="filterByStatus('已完结')"
        >
          已完结
        </view>
        <view 
          class="filter-tab" 
          :class="{ active: selectedStatus === '异常' }"
          @click="filterByStatus('异常')"
        >
          异常
        </view>
      </view>
    </view>

    <!-- 数据展示 -->
    <view class="data-list">
      <view v-if="auditList">
        <view v-for="(item, index) in auditList" :key="index" class="project-card">
          <!-- 卡片头部 -->
          <view class="card-header">
            <view class="project-title">
              <text class="project-name">{{ item.project_name || '未知项目' }}</text>
              <text class="customer-name">{{ item.customer_name || '未知客户' }}</text>
            </view>
         
            <view v-if="item.status === '已签约' || item.status === '收款计划审批' || item.status === '收款中'" class="status-tag status-yellow">
              待审批
            </view>
            <view v-else-if="item.status === '已开工'" class="status-tag status-blue">
              {{ item.status }}
            </view>
            <view v-else-if="item.status === '收款中'" class="status-tag status-red">
              {{ item.status }}
            </view>
            <view v-else-if="item.status === '已完结'" class="status-tag status-green">
              {{ item.status }}
            </view>
            <view v-else-if="item.status === '异常'" class="status-tag status-red">
              {{ item.status }}
            </view>
            <view v-else class="status-tag status-gray">
              {{ item.status || '未知' }}
            </view>
          </view>
          
          <!-- 卡片内容 -->
          <view class="card-body">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">客户等级</text>
                <text class="info-value level-tag">{{ item.customer_level || '未知' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">生产数量</text>
                <text class="info-value">{{ item.production_quantity || '未知' }}</text>
              </view>
            </view>
            
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">合同金额</text>
                <text class="info-value money">{{ item.contract_money || '0' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">负责人</text>
                <text class="info-value">{{ item.manager_phone || '未知' }}</text>
              </view>
            </view>
            
            <view class="info-row">
              <view class="info-item full-width">
                <text class="info-label">创建时间</text>
                <text class="info-value">{{ item.createtime || '未知' }}</text>
              </view>
            </view>
          </view>
          
          <!-- 卡片底部 -->
          <view class="card-footer">
            <button class="action-btn" @click="goToAudit(item, index)">
              <text class="btn-text">{{ item.status === '已完结' ? '查看' : '进入审核' }}</text>
              <text class="btn-arrow">→</text>
            </button>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-else class="empty">
        <text>暂无数据</text>
      </view>
    </view>
    
    <!-- 自定义底部栏 -->
    <CustomTabbar :tabList="tabList" :current="currentTabIndex" />
  </view>
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/CustomTabbar.vue'
import { getTabListByRole } from '@/utils/tabberList.js'

export default {
  components: {
    CustomTabbar
  },
  data() {
    return {
      currentRole: null,
      auditList: [],
      selectedStatus: 'all',
      tabList: [],
      currentTabIndex: 0
    }
  },
  
  computed: {
    roleText() {
      if (this.currentRole === 4) return '经理端';
      if (this.currentRole === 2) return '财务端';
      return '未知角色';
    }
  },
  
  onShow() {
    this.initPage();
  },
  
  methods: {
    // 获取状态数量
    getStatusCount(status) {
      const base = this._allList || this.auditList || [];
      if (!Array.isArray(base)) {
        return 0;
      }
      
      if (status === 'all') {
        return base.length;
      } else if (status === 'pending') {
        // 待审批：包括 收款计划审批、收款中
        return base.filter(item => {
          const s = item.status || '';
          return s === '收款计划审批' || s === '收款中';
        }).length;
      } else {
        // 根据状态精确匹配统计
        const count = base.filter(item => {
          return item.status && item.status === status;
        }).length;
        
        // 添加调试信息
        if (status === '已完结') {
          console.log('已完结状态统计:', {
            totalItems: base.length,
            status: status,
            count: count,
            allStatuses: base.map(item => item.status)
          });
        }
        
        return count;
      }
    },
    
    // 按状态筛选
    filterByStatus(status) {
      this.selectedStatus = status;
      const all = this._allList || [];
      if (status === 'all') {
        this.auditList = all;
        return;
      }
      if (status === 'pending') {
        this.auditList = all.filter(item => {
          const s = item.status || '';
          return s === '收款计划审批' || s === '收款中';
        });
        return;
      }
      this.auditList = all.filter(item => item.status === status);
    },
    
    // 初始化页面
    async initPage() {
      try {
        await this.getUserRole();
        await this.loadAuditData();
      } catch (error) {
        console.error('页面初始化失败:', error);
      }
    },
    
    // 获取用户角色
    getUserRole() {
      let role = uni.getStorageSync('user-role');
      let roleId = uni.getStorageSync('user-role-id');
      
      if (typeof role === 'string') {
        if (role === 'manager') role = 4;
        else if (role === 'finance') role = 2;
        else if (role === 'sales') role = 1;
        else if (role === 'production') role = 3;
      }
      
      if (!role && roleId) {
        role = roleId;
      }
      
      if (!role) {
        role = 4;
      }
      
      this.currentRole = role;
      
      // 初始化tabbar配置
      this.initTabbar();
    },
    
    // 初始化tabbar配置
    initTabbar() {
      // 获取当前角色的tabbar配置
      this.tabList = getTabListByRole(this.currentRole);
      
      // 找到当前页面在tabbar中的索引
      const currentPagePath = 'pages/boss/audit';
      this.currentTabIndex = this.tabList.findIndex(item => item.pagePath === currentPagePath);
      
      // 如果没找到，默认使用第一个
      if (this.currentTabIndex === -1) {
        this.currentTabIndex = 0;
      }
    },
    
    // 加载审核数据
    async loadAuditData() {
      try {
        const response = await uni.request({
          url: 'https://data.web1995.top/api/project/getJlReviewList',
          method: 'POST',
          data: { page: 1, limit: 20, keyword: '' },
          header: { 'token': uni.getStorageSync('sc-token') || '' }
        });
        const list = response?.data?.data?.list || [];
        
        // 添加调试信息
        console.log('审核数据加载完成:', {
          totalCount: list.length,
          statuses: list.map(item => item.status),
          completedItems: list.filter(item => item.status === '已完结')
        });
        
        // 原始数据缓存，便于本地筛选切换
        this._allList = list;
        this.auditList = list;
      } catch (error) {
        console.error('加载审核数据失败:', error);
        this._allList = [];
        this.auditList = [];
      }
    },

    // 跳转到审核页面
    goToAudit(item, index) {
      try {
        uni.navigateTo({
          url: '/pages/boss/audit-detail',
          success: (res) => {
            res.eventChannel.emit('acceptDataFromOpenerPage', { data: item });
          }
        });
      } catch (error) {
        console.error('跳转异常:', error);
        uni.showToast({
          title: '跳转异常',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style scoped>
.audit-page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 0;
  padding-bottom: 120rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx 30rpx 30rpx;
  box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.08);
  border-bottom: 1rpx solid #e2e8f0;
}

.title {
  font-size: 40rpx;
  font-weight: 800;
  color: #1a202c;
  display: block;
  margin-bottom: 8rpx;
  letter-spacing: -0.5rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #718096;
  display: block;
  font-weight: 500;
}

.status-filter {
  background: #fff;
  padding: 20rpx 24rpx;
  border-bottom: 1rpx solid #e2e8f0;
}

.filter-row {
  display: flex;
  gap: 12rpx;
  margin-bottom: 12rpx;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-tab {
  flex: 1;
  padding: 16rpx 12rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
  font-weight: 500;
  color: #64748b;
  background: #f1f5f9;
  text-align: center;
  transition: all 0.3s ease;
  border: 1rpx solid transparent;
  min-height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.filter-tab.active {
  background: #3b82f6;
  color: #fff;
  border-color: #3b82f6;
  box-shadow: 0 2rpx 8rpx rgba(59, 130, 246, 0.3);
}

.filter-tab:active {
  transform: scale(0.98);
}

.data-list {
  padding: 30rpx 24rpx;
}

.project-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #e2e8f0;
  overflow: hidden;
  transition: all 0.3s ease;
}

.project-card:active {
  transform: translateY(-2rpx);
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 1rpx solid #f1f5f9;
}

.project-title {
  flex: 1;
}

.project-name {
  font-size: 32rpx;
  font-weight: 700;
  color: #1a202c;
  display: block;
  margin-bottom: 8rpx;
  line-height: 1.4;
}

.customer-name {
  font-size: 24rpx;
  color: #64748b;
  background: #f1f5f9;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  display: inline-block;
  font-weight: 500;
}

.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 600;
  min-width: 80rpx;
  text-align: center;
  color: #fff;
}

.status-yellow {
  background: #f59e0b;
}

.status-blue {
  background: #3b82f6;
}

.status-red {
  background: #ef4444;
}

.status-green {
  background: #10b981;
}

.status-gray {
  background: #6b7280;
}

.card-body {
  padding: 24rpx 32rpx;
}

.info-row {
  display: flex;
  margin-bottom: 20rpx;
  gap: 20rpx;
}

.info-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.info-item.full-width {
  flex: 100%;
}

.info-label {
  font-size: 22rpx;
  color: #64748b;
  font-weight: 500;
}

.info-value {
  font-size: 26rpx;
  color: #1a202c;
  font-weight: 600;
}

.info-value.money {
  color: #dc2626;
  font-weight: 700;
  font-size: 28rpx;
}

.info-value.level-tag {
  background: #dbeafe;
  color: #1d4ed8;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 22rpx;
  font-weight: 600;
  width: fit-content;
}

.card-footer {
  padding: 12rpx 32rpx 16rpx;
  border-top: 1rpx solid #f1f5f9;
  text-align: center;
}

.action-btn {
  background: #3b82f6;
  color: #fff;
  font-size: 28rpx;
  font-weight: 600;
  padding: 10rpx 24rpx;
  border-radius: 12rpx;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.3);
  transition: all 0.2s ease;
  min-height: 40rpx;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 280rpx;
}

.action-btn:active {
  transform: translateY(1rpx);
  box-shadow: 0 2rpx 8rpx rgba(59, 130, 246, 0.4);
  background: #2563eb;
}

.btn-text {
  margin-right: 8rpx;
}

.btn-arrow {
  font-size: 24rpx;
  font-weight: 700;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: calc(100vh - 300rpx);
  padding: 100rpx 40rpx;
  text-align: center;
  color: #94a3b8;
  font-size: 28rpx;
  font-weight: 500;
}
</style>